import { Component, ReactNode } from "react";
import { Button, Popconfirm,Tag, Table, message, Select,Input, Space,Switch,Tooltip,Modal} from "antd";
import { instance } from "../../utils/request";

const { Option } = Select;
import {DeleteOutlined,SearchOutlined,LineHeightOutlined} from "@ant-design/icons";
const { Search } = Input;
import AddNotice from "./AddNotice"; 
import EditNotice from "./EditNotice"; 
class NoticesList extends Component {
  state = {
    dataSource: [], // 添加初始化的dataSource属性
    total: 0, // 总条数
    pagenum: 1, // 当前页
    pagesize: 5, // 显示数量
    noticeName: "", 
    noticeStatus: 2, // 默认
    showAddNoticeDialog: false, // 是否隐藏
    showEditNoticeDialog: false, // 是否隐藏
    editData: {}, //编辑显示的商品数据
  };
  loadData = () => {
    const params = {
      pagenum: this.state.pagenum,
      pagesize: this.state.pagesize,
      noticeName: this.state.noticeName,
      noticeStatus: this.state.noticeStatus,    
    };

    instance.get("/notices", { params }).then((res) => {
      this.setState({
        dataSource: res.data.data.data,
        total: res.data.data.total,
      });
    });
  };

  handleEdit = (record: any) => {
    instance.get(`notices/${record}`).then((res) => {
      console.log('res返回的数据1111111',res.data.data[0])
      this.setState({
        editData: res.data.data[0],
        showEditNoticeDialog: true,
      });
    });
  };
// 22章
  showEditDialog = (falg: any) => {
    if (falg) {
      return (
        <EditNotice
          visible={this.state.showEditNoticeDialog}
          closeModal={this.closeEditDialog}
          data={this.state.editData}
        ></EditNotice>
      );
    }
  };

  onSearch = (value: any) => {
    this.setState(
      (preState: any) => {
        preState.query = value;
      },
      () => {
        this.loadData();
      }
    );
  };

  // 分页，点击页、显示数量
  changePage = (page: number, pagesize: number) => {
    this.setState({ pagenum: page, pagesize: pagesize }, () => {
      this.loadData();
    });
  };

  handleDelete = (id: any) => {
    instance.delete(`/notices/${id}`).then((res) => {
      if (res.data.meta.status === 200) {
        message.success("删除成功!");
        this.loadData();
      } else {
        message.error("删除失败!");
      }
    });
  };

  // 添加商品
  handleSendNotice = () => {
    this.setState({ showAddNoticeDialog: true });
  };
  // 关闭添加窗口
  closeAddDialog = () => {
    this.setState({ showAddNoticeDialog: false }, () => {
      this.loadData();
    });
    // 重新进行更新刷新页面
  };
  closeEditDialog = () => {
    this.setState({ showEditNoticeDialog: false }, () => {
      this.loadData();
    });
    // 重新进行更新刷新页面
  };
  enableChange = (noticeId:any) => {
    
    instance.get(`notices/${noticeId}`).then(res=>{
      let  noticeStatus=res.data.data[0].notice_status
      
      if(noticeStatus===0){
        noticeStatus=1
      }else if(noticeStatus===1){
        noticeStatus=0
      }
      // 取反传递、查询状态
      instance.put(`notices/${noticeId}/state/${noticeStatus}`).then(res=>{
        if(res.data.meta.status ===200){
          message.success('用户状态更改成功')
          this.loadData()
        }
      })
      
    }

    ).catch(res=>{
      
    })
    
};
    onClear=()=>{

      this.setState({ noticeName: '', noticeStatus:2}, () => {
        this.loadData();
      });

    };
  // 组件加载完挂载
  componentDidMount() {
    this.loadData();
  };
  showCard = (content: any) => {
    Modal.info({
      title: "公告详情",
      content: content,
    });
  }

  render() {
    const columns = [
      {
        title: "序号",
        dataIndex: "notice_id",
        key: "notice_id",
      },
      {
        title: "公告名称",
        dataIndex: "notice_name",
        key: "notice_name",
      },
      {
        title: "公告内容",
        dataIndex: "notice_content",
        key: "notice_content",
        render: (text :any) => (
            <Tooltip title={text}>
              <a onClick={() => this.showCard(text)}>{text.slice(0, 5)}...</a> {/* 假设只显示公告内容的前10个字符 */}
            </Tooltip>
          ),
      },
      {
        title: "发布时间",
        dataIndex: "create_time",
        key: "create_time",
      },
      {
        title: "公告类型",
        dataIndex: "notice_type",
        key: "notice_type",
        render: (status: any) => (
            <Tag color={status === 1 ? 'green' : 'red'}>
              {status === 1 ? '公告' : '通知'}
            </Tag>
        ),
      },
      {
        title: '发布状态',
        dataIndex: 'notice_id',
        key: 'notice_id',
        render: (noticeId: any, record: any) => {
          const { notice_status } = record;
          console.log('record的值',record)
          return (
            <Switch
              checkedChildren="启用"
              unCheckedChildren="停用"
              checked={notice_status === 0}
              onChange={() => this.enableChange(noticeId)}
            />
          );
        },
      },
      {
        title: "操作",
        dataIndex: "notice_id",
        key: "notice_id",
        render: (record: any) => (
          <>
            <Button
              onClick={() => {
                this.handleEdit(record);
              }}
              style={{ marginRight: "10px" }}
            >
              编辑
            </Button>
            <Popconfirm
              okText="确认"
              cancelText="取消"
              title="你确认要删除该记录嘛?"
              onConfirm={() => {
                this.handleDelete(record);
              }}
            >
              <Button type="primary">删除</Button>
            </Popconfirm>
          </>
        ),
      },
    ];
    return (
      <div>
        <Space style={{ marginBottom: 20, marginTop: 10 }}>
          公告名称:
          <Input
            size="large"
            placeholder="请输入公告名称"
            value={this.state.noticeName}
            onChange={(e) => this.setState({ noticeName: e.target.value })}
            allowClear
          />
            公告状态:
            <Select size="large" placeholder="选择公告状态" style={{width:'180px'}}>
            <Option value="0">启用</Option>
            <Option value="1">禁用</Option>
          </Select>
          <Button type="primary" size="large" onClick={this.onSearch}>
            搜索 <SearchOutlined />
          </Button>

        </Space>
        <Button
          style={{ marginTop: "7px", marginLeft: "10px" }}
          onClick={this.handleSendNotice}
          size="large"
          type="primary"
        >
          发布公告 <LineHeightOutlined />
        </Button>

        <Button
          style={{ marginTop: "7px", marginLeft: "10px" }}
          onClick={this.onClear}
          size="large"
          type="primary"
        >
          清除条件<DeleteOutlined />
        </Button>

        <Table
          dataSource={this.state.dataSource}
          columns={columns}
          rowKey="notice_id"
          pagination={{
            pageSize: this.state.pagesize,
            defaultCurrent: this.state.pagenum,
            onChange: this.changePage,
            total: this.state.total,
          }}
        />
           <AddNotice
          close={this.closeAddDialog}
          visible={this.state.showAddNoticeDialog}
        />
            {/*  当点击编辑的时候会变成true，发送异步请求后，展示 */}
            {this.showEditDialog(this.state.showEditNoticeDialog)}

      </div>
    );
  }
}

export default NoticesList;
